<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * App\Models\Order
 *
 * @property int $id
 * @property string $openid openid
 * @property int $status 1-未支付，2-已支付，3-已退款
 * @property int $wechat_upload_id 1-图片,2-视频
 * @property \Carbon\Carbon|null $created_at
 * @property \Carbon\Carbon|null $updated_at
 * @property string|null $deleted_at
 * @property-read mixed $wechat_pay_order_number
 * @method static bool|null forceDelete()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Order onlyTrashed()
 * @method static bool|null restore()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereOpenid($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereStatus($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Order whereWechatUploadId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Order withTrashed()
 * @method static \Illuminate\Database\Query\Builder|\App\Models\Order withoutTrashed()
 * @mixin \Eloquent
 */
class Order extends Model
{
    use SoftDeletes;

    protected $fillable = ['openid', 'wechat_upload_id'];

    const STATUSES = [
        1 => '未支付',
        2 => '已支付',
        3 => '已退款',
    ];

    protected static function boot()
    {
        $setNumber = function(Order $order) {
            if (!strlen($order->number)) {
                $order->number = 'UPLOAD' . date('YmdHis') . substr(uniqid(), 0, 12);
            }
        };
        parent::boot();
        static::creating(function(Order $order) {
            if (empty($order->status)) {
                $order->status = 1;
            }
        });
        static::created($setNumber);
        static::saving($setNumber);
    }

    public function wechat_upload()
    {
        return $this->belongsTo(WechatUpload::class);
    }

    public function getStatusWordAttribute()
    {
        if (array_key_exists($this->status, self::STATUSES)) {
            return self::STATUSES[$this->status];
        }
        return '未知';
    }

    public function member() : Relation
    {
        return $this->hasOne(Member::class, 'openid', 'openid');
    }
}
